package com.globallogic.vkulyk.SSHTool;

import java.io.InputStream;
import com.jcraft.jsch.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CommandExecutor extends ActionExecutor {
	private String command = "";
	private final Logger logger = LoggerFactory
			.getLogger(CommandExecutor.class);

	public CommandExecutor(String hostArg, int portArg,
			String userArg, String passwordArg, String commandArg) {
		super(hostArg, portArg, userArg, passwordArg);
		command = commandArg;
	}

	public void execute() {
		Session session = openSession();
		executeInExistingSession(session);
		closeSession(session);
	}

	@Override
	public void executeInExistingSession(Session sessionArg) {
		Session session = sessionArg;
		logger.debug("Opening exec channel for command '" + command + "'..");
		try {
			Channel channel = session.openChannel("exec");
			ChannelExec channelExec = (ChannelExec) channel;
			channelExec.setCommand(command);
			channel.setInputStream(null);
			channelExec.setErrStream(System.err);
			InputStream in = channel.getInputStream();

			logger.debug("Executing command '" + command + "'");
			channel.connect();

			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					System.out.print(new String(tmp, 0, i));
				}
				if (channel.isClosed()) {
					logger.debug("Command exit-status: {}",
							channel.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}
			logger.debug("Closing exec channel..");
			channel.disconnect();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}

}
